window.onload = () => {
  const box = document.getElementById('box')
  const toggleBtn = document.getElementById('toggle-btn')
  let isVisible = false

  toggleBtn.addEventListener('click', () => {
    if (isVisible) {
      // 隐藏元素 - 先开始动画
      box.classList.remove('visible')
      // 动画结束后再隐藏display
      box.addEventListener('transitionend', handleTransitionEnd, {once: true})
    } else {
      // 显示元素 - 先设置display
      box.classList.add('show')
      // 下一帧开始动画
      requestAnimationFrame(() => {
        box.classList.add('visible')
      })
    }
    isVisible = !isVisible
  })
  function handleTransitionEnd(e) {
    // 确保是opacity或transform过渡完成
    if ((e.propertyName === 'opacity' || e.propertyName === 'transform') && !isVisible) {
      box.classList.remove('show')
    }
  }
}
